#include <stdlib.h>
#include "util.h"
#include "sorting.hpp"

#define SORTING_ALG_BB      1
#define SORTING_ALG_MER     2
#define SORTING_ALG_HEAP    3

int debug = 0;

static bool checksort(vector<int> &a)
{
    if (a.size() < 2)
        return true;

    for (int i = 0; i < (int)(a.size()-1); i++) {
        if (a[i] > a[i+1])
            return false;
    }
    return true;
}

int main(int argc, char *argv[])
{
    int alg = -1;
    int num = 10;
    vector<int> a;
    vector<int>::iterator it;

    if (argc < 2) {
        cout << "usage: sorting <alg> [size] [debug]" << endl;
        cout << "       alg = 1: bubble sort " << endl;
        cout << "       alg = 2: merge sort  " << endl;
        cout << "       alg = 3: heap sort   " << endl;
        return -1;
    }

    alg = atoi(argv[1]);
    if (argc > 2) {
        num = atoi(argv[2]);
        if (num < 0) {
            cout << "invalid array size " << num <<endl;
            return -1;
        }
    }
    if (argc > 3)
        debug = atoi(argv[2]);

    srand(time(0));
    for (int i=0; i<num; i++)
    {
        a.push_back(rand() % 1000);
    }

    // print unsorted array
    cout << "unsorted array" << endl;
    for ( it=a.begin() ; it < a.end(); it++ )
            cout << " " << *it;
    cout << endl << endl;

    switch (alg) {
        case SORTING_ALG_BB:
            cout << "performing bubble sort " << endl;
            bbsort(a);
            break;
        case SORTING_ALG_MER:
            cout << "performing merge sort " << endl;
            mergesort(a);
            break;
        case SORTING_ALG_HEAP:
            cout << "performing heap sort " << endl;
            heapsort(a);
            break;
        default:
            cout << "unknown sorting alg " << alg << endl;
            break;
    }

    // print sorted array
    cout << "output array" << endl;
    for ( it=a.begin() ; it < a.end(); it++ )
            cout << " " << *it;
    cout << endl << endl;

    if (checksort(a))
        cout << "output array is indeed sorted!" << endl;
    else
        cout << "output array is not fully sorted!" << endl;

    return 0;
}
